/**
 * 响应工具类
 */

// 响应码枚举
export enum ResponseCode {
  SUCCESS = 200,
  CREATED = 201,
  NO_CONTENT = 204,
  BAD_REQUEST = 400,
  UNAUTHORIZED = 401,
  FORBIDDEN = 403,
  NOT_FOUND = 404,
  INTERNAL_ERROR = 500,
}

// 响应消息枚举
export enum ResponseMessage {
  SUCCESS = '操作成功',
  CREATED = '创建成功',
  NO_CONTENT = '无内容',
  BAD_REQUEST = '请求参数错误',
  UNAUTHORIZED = '未授权',
  FORBIDDEN = '禁止访问',
  NOT_FOUND = '资源不存在',
  INTERNAL_ERROR = '服务器内部错误',
}

// 响应结构接口
export interface ResponseResult<T = any> {
  code: number;
  message: string;
  data?: T;
  timestamp: number;
}

/**
 * 响应结果工具类
 */
export class R {
  /**
   * 成功响应
   * @param data 响应数据
   * @param message 响应消息
   * @returns 响应结果
   */
  public static ok<T = any>(
    data?: T,
    message: string = ResponseMessage.SUCCESS,
  ): ResponseResult<T> {
    return {
      code: ResponseCode.SUCCESS,
      message,
      data,
      timestamp: Date.now(),
    };
  }

  /**
   * 创建成功响应
   * @param data 响应数据
   * @param message 响应消息
   * @returns 响应结果
   */
  public static created<T = any>(
    data?: T,
    message: string = ResponseMessage.CREATED,
  ): ResponseResult<T> {
    return {
      code: ResponseCode.CREATED,
      message,
      data,
      timestamp: Date.now(),
    };
  }

  /**
   * 无内容响应
   * @param message 响应消息
   * @returns 响应结果
   */
  public static noContent(
    message: string = ResponseMessage.NO_CONTENT,
  ): ResponseResult<null> {
    return {
      code: ResponseCode.NO_CONTENT,
      message,
      timestamp: Date.now(),
    };
  }

  /**
   * 错误响应
   * @param code 错误码
   * @param message 错误消息
   * @returns 响应结果
   */
  public static error(
    code: number = ResponseCode.INTERNAL_ERROR,
    message: string = ResponseMessage.INTERNAL_ERROR,
  ): ResponseResult<null> {
    return {
      code,
      message,
      timestamp: Date.now(),
    };
  }

  /**
   * 请求参数错误响应
   * @param message 错误消息
   * @returns 响应结果
   */
  public static badRequest(
    message: string = ResponseMessage.BAD_REQUEST,
  ): ResponseResult<null> {
    return this.error(ResponseCode.BAD_REQUEST, message);
  }

  /**
   * 未授权响应
   * @param message 错误消息
   * @returns 响应结果
   */
  public static unauthorized(
    message: string = ResponseMessage.UNAUTHORIZED,
  ): ResponseResult<null> {
    return this.error(ResponseCode.UNAUTHORIZED, message);
  }

  /**
   * 禁止访问响应
   * @param message 错误消息
   * @returns 响应结果
   */
  public static forbidden(
    message: string = ResponseMessage.FORBIDDEN,
  ): ResponseResult<null> {
    return this.error(ResponseCode.FORBIDDEN, message);
  }

  /**
   * 资源不存在响应
   * @param message 错误消息
   * @returns 响应结果
   */
  public static notFound(
    message: string = ResponseMessage.NOT_FOUND,
  ): ResponseResult<null> {
    return this.error(ResponseCode.NOT_FOUND, message);
  }
}
